package ewasteclient;

import javax.swing.JOptionPane;

/**
 * Client application for E-Waste Collector.
 *
 * {@code EWasteClient} is the client application for E-Waste Collector allowing the user to submit
 * descriptions of items along with the address to pick them up at to schedule a pickup with the
 * server.
 * @author shardul
 */
public class EWasteClient extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    // default messages
    private static String addrHelp = "<address here>";
    private static String descHelp = "<description here>";
    private static String itemHelp = "<item>";
    // button options
    private static String options[] = {"Submit more", "Exit application"};
    private static String server;
    private static int PORT = 30303;

    /**
     * Creates new form EWasteClient
     */
    public EWasteClient() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        welcomePane = new javax.swing.JScrollPane();
        welcome = new javax.swing.JTextArea();
        descPane = new javax.swing.JScrollPane();
        desc = new javax.swing.JTextArea();
        item = new javax.swing.JTextField();
        addrPane = new javax.swing.JScrollPane();
        addr = new javax.swing.JTextArea();
        submit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("EWasteCollector");
        setResizable(false);

        welcome.setEditable(false);
        welcome.setBackground(new java.awt.Color(238, 238, 238));
        welcome.setColumns(20);
        welcome.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        welcome.setLineWrap(true);
        welcome.setRows(5);
        welcome.setText("       Welcome to the E-Waste Collector!\n\n  Please describe your waste items and enter\n                  your street address.");
        welcome.setWrapStyleWord(true);
        welcomePane.setViewportView(welcome);

        desc.setColumns(15);
        desc.setLineWrap(true);
        desc.setRows(5);
        desc.setText(descHelp);
        desc.setWrapStyleWord(true);
        desc.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                descFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                descFocusLost(evt);
            }
        });
        descPane.setViewportView(desc);

        item.setText(itemHelp);
        item.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                itemFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                itemFocusLost(evt);
            }
        });

        addrPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

        addr.setColumns(20);
        addr.setRows(5);
        addr.setText(addrHelp);
        addr.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                addrFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                addrFocusLost(evt);
            }
        });
        addrPane.setViewportView(addr);

        submit.setText("Submit");
        submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(welcomePane, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(item)
                    .addComponent(descPane)
                    .addComponent(addrPane))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(153, 153, 153)
                .addComponent(submit)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(welcomePane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(item, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(descPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addrPane, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(submit)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addrFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_addrFocusGained
        if (addr.getText().equals(addrHelp)) {
            addr.setText(null);
        }
    }//GEN-LAST:event_addrFocusGained

    private void addrFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_addrFocusLost
        if (addr.getText().isEmpty()) {
            addr.setText(addrHelp);
        }
    }//GEN-LAST:event_addrFocusLost

    private void descFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descFocusGained
        if (desc.getText().equals(descHelp)) {
            desc.setText(null);
        }
    }//GEN-LAST:event_descFocusGained

    private void descFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descFocusLost
        if (desc.getText().isEmpty()) {
            desc.setText(descHelp);
        }
    }//GEN-LAST:event_descFocusLost

    private void itemFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_itemFocusGained
        if (item.getText().equals(itemHelp)) {
            item.setText(null);
        }
    }//GEN-LAST:event_itemFocusGained

    private void itemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_itemFocusLost
        if (item.getText().isEmpty()) {
            item.setText(itemHelp);
        }
    }//GEN-LAST:event_itemFocusLost

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
        String date = null;
        try (java.net.Socket sock = new java.net.Socket(server, PORT);
                java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(sock.getOutputStream())) {
            // write data
            out.writeUTF(addr.getText());
            out.writeUTF(desc.getText());
            out.writeUTF(item.getText());
            // flush to force write
            out.flush();
            java.io.ObjectInputStream in = new java.io.ObjectInputStream(sock.getInputStream());
            // read next collection date
            date = in.readUTF();
            in.close();
        } catch (java.net.UnknownHostException ex) {
            System.err.println("Caught UnknownHostException: " + ex.getLocalizedMessage());
            System.exit(-1);
        } catch (java.io.IOException ex) {
            System.err.println("Caught IOException: " + ex.getLocalizedMessage());
            System.exit(-2);
        }
        // display message and ask for exit or more submissions
        String msg = "Your request was sent successfully. Your " +
                item.getText() + " will be collected on " + date + ".";
        int choice = JOptionPane.showOptionDialog(this, msg, "Request Successful",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (choice == 1) {
            System.exit(0);
        } else {
            addr.setText(addrHelp);
            desc.setText(descHelp);
            item.setText(itemHelp);
        }
    }//GEN-LAST:event_submitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        server = (args.length == 0)? "localhost": args[0];
        // Create and display the form
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EWasteClient().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea addr;
    private javax.swing.JScrollPane addrPane;
    private javax.swing.JTextArea desc;
    private javax.swing.JScrollPane descPane;
    private javax.swing.JTextField item;
    private javax.swing.JButton submit;
    private javax.swing.JTextArea welcome;
    private javax.swing.JScrollPane welcomePane;
    // End of variables declaration//GEN-END:variables
}
